package org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.persistence;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import jakarta.annotation.Resource;
import org.framework.lazy.cloud.network.heartbeat.common.ChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.ClientProxyRoute;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteContext;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteType;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.virtual.route.LazyNettyClientVirtualRoute;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.virtual.route.LazyNettyClientVirtualRouteRepository;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.converter.LazyNettyClientVirtualRouteConverter;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyClientVirtualRouteDO;
import org.springframework.stereotype.Repository;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazySetValueWrappers;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe 客户端虚拟路由管理
 *
 * @author Jia wei Wu
 * @date 2025/05/06 05:00 下午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Repository
public class LazyNettyClientVirtualRouteRepositoryImpl implements LazyNettyClientVirtualRouteRepository {

    @Resource
    LazyLambdaStream lazyLambdaStream;

    /**
     * describe 新增客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRoute 新增客户端虚拟路由管理
     * @return {@link Result<LazyNettyClientVirtualRoute>} 客户端虚拟路由管理新增后领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyClientVirtualRoute> story(LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        lazyLambdaStream.upsert(lazyNettyClientVirtualRouteDO);

        // 更新服务端路由
        String virtualIp = lazyNettyClientVirtualRoute.getVirtualIp();
        String virtualPort = lazyNettyClientVirtualRoute.getVirtualPort();
        String targetIp = lazyNettyClientVirtualRoute.getTargetIp();
        String targetPort = lazyNettyClientVirtualRoute.getTargetPort();
        String targetClientId = lazyNettyClientVirtualRoute.getTargetClientId();

        ClientProxyRoute serverProxyClientRoute = new ClientProxyRoute();
        serverProxyClientRoute.setVirtualIp(virtualIp);
        serverProxyClientRoute.setVirtualPort(virtualPort);
        serverProxyClientRoute.setTargetClientId(targetClientId);
        serverProxyClientRoute.setTargetIp(targetIp);
        serverProxyClientRoute.setTargetPort(targetPort);
        serverProxyClientRoute.setRouteType(RouteType.SERVER_PROXY_CLIENT);
        RouteContext.setRoute(serverProxyClientRoute);


        ClientProxyRoute clientProxyRoute = new ClientProxyRoute();
        clientProxyRoute.setVirtualIp(virtualIp);
        clientProxyRoute.setVirtualPort(virtualPort);
        clientProxyRoute.setTargetClientId(targetClientId);
        clientProxyRoute.setTargetIp(targetIp);
        clientProxyRoute.setTargetPort(targetPort);
        clientProxyRoute.setRouteType(RouteType.CLIENT_PROXY_CLIENT);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((serverClient, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_CLIENT_ROUTE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });

        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRouteList 批量新增客户端虚拟路由管理
     * @return {@link Result<List<LazyNettyClientVirtualRoute>>} 客户端虚拟路由管理新增后领域对象集合
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<List<LazyNettyClientVirtualRoute>> batchStory(List<LazyNettyClientVirtualRoute> lazyNettyClientVirtualRouteList) {
        List<LazyNettyClientVirtualRouteDO> lazyNettyClientVirtualRouteDOList = lazyNettyClientVirtualRouteList.stream().map(LazyNettyClientVirtualRouteConverter.INSTANCE::fromLazyNettyClientVirtualRoute).collect(Collectors.toList());
        lazyLambdaStream.upsert(lazyNettyClientVirtualRouteDOList);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRoute 查询单个客户端虚拟路由管理
     * @return {@link Result<LazyNettyClientVirtualRoute>} 客户端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyClientVirtualRoute> findOne(LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        lazyNettyClientVirtualRouteDO.setIsDeleted(false);
        LazyNettyClientVirtualRoute lazyNettyClientVirtualRouteOne = lazyLambdaStream.selectOne(LazyWrappers.lambdaWrapperBean(lazyNettyClientVirtualRouteDO), LazyNettyClientVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyClientVirtualRouteOne);
    }

    /**
     * describe 查询多个客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRoute 查询多个客户端虚拟路由管理
     * @return {@link Result<List<LazyNettyClientVirtualRoute>>} 客户端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<List<LazyNettyClientVirtualRoute>> findList(LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        List<LazyNettyClientVirtualRoute> lazyNettyClientVirtualRouteList = lazyLambdaStream.selectList(LazyWrappers.lambdaWrapperBean(lazyNettyClientVirtualRouteDO), LazyNettyClientVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyClientVirtualRouteList);
    }

    /**
     * describe 分页查询多个客户端虚拟路由管理
     *
     * @param size                        当前页数
     * @param current                     当前页
     * @param lazyNettyClientVirtualRoute 分页查询多个客户端虚拟路由管理
     * @return {@link Result<LazyPage<LazyNettyClientVirtualRoute>>} 分页客户端虚拟路由管理领域对象
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyPage<LazyNettyClientVirtualRoute>> findPage(int size, int current, LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        LazyPage<LazyNettyClientVirtualRoute> lazyPage = new LazyPage<>(current, size);
        LazyPage<LazyNettyClientVirtualRoute> lazyNettyClientVirtualRouteLazyPage = lazyLambdaStream.selectPage(LazyWrappers.lambdaWrapperBean(lazyNettyClientVirtualRouteDO), lazyPage, LazyNettyClientVirtualRoute.class);
        return ResultFactory.successOf(lazyNettyClientVirtualRouteLazyPage);
    }

    /**
     * describe 删除客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRoute 删除客户端虚拟路由管理
     * @return {@link Result<LazyNettyClientVirtualRoute>} 客户端虚拟路由管理
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<LazyNettyClientVirtualRoute> remove(LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        lazyLambdaStream.update(LazySetValueWrappers.<LazyNettyClientVirtualRouteDO>lambdaWrapper()
                        .set(LazyNettyClientVirtualRouteDO::getIsDeleted, true),
                LazyWrappers
                        .<LazyNettyClientVirtualRouteDO>lambdaWrapper()
                        .eq(LazyNettyClientVirtualRouteDO::getId, lazyNettyClientVirtualRouteDO.getId())

        );

        LazyNettyClientVirtualRouteDO clientVirtualRouteDO = lazyLambdaStream.selectOne(
                LazyWrappers
                        .<LazyNettyClientVirtualRouteDO>lambdaWrapper()
                        .eq(LazyNettyClientVirtualRouteDO::getId, lazyNettyClientVirtualRouteDO.getId())
        );
        String virtualIp = clientVirtualRouteDO.getVirtualIp();
        String virtualPort = clientVirtualRouteDO.getVirtualPort();
        String targetIp = clientVirtualRouteDO.getTargetIp();
        String targetPort = clientVirtualRouteDO.getTargetPort();
        String targetClientId = clientVirtualRouteDO.getTargetClientId();


        ClientProxyRoute clientProxyRoute = new ClientProxyRoute();
        clientProxyRoute.setTargetClientId(targetClientId);
        clientProxyRoute.setVirtualIp(virtualIp);
        clientProxyRoute.setVirtualPort(virtualPort);
        clientProxyRoute.setTargetIp(targetIp);
        clientProxyRoute.setTargetPort(targetPort);
        clientProxyRoute.setRouteType(RouteType.CLIENT_PROXY_CLIENT);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((channelClientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_CLIENT_ROUTE_CLOSE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在客户端虚拟路由管理
     *
     * @param lazyNettyClientVirtualRoute 客户端虚拟路由管理领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2025/05/06 05:00 下午
     **/

    @Override
    public Result<Boolean> exists(LazyNettyClientVirtualRoute lazyNettyClientVirtualRoute) {
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = LazyNettyClientVirtualRouteConverter.INSTANCE.fromLazyNettyClientVirtualRoute(lazyNettyClientVirtualRoute);
        Boolean exists = lazyLambdaStream.exists(LazyWrappers.lambdaWrapperBean(lazyNettyClientVirtualRouteDO));
        return ResultFactory.successOf(exists);
    }

}